﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using SalesSys.Comm.BLL;
using SalesSys.Comm.DAL;
using SalesSys.Comm.Utility;

namespace SalesSys.WebCore
{          
    public class BaseController : Controller
    {
        public BaseController()
        {
            //this.CurrNavType = EnumHelp.NavType.Home;
        }


        const string LoginTokenKey = "LoginToken";
        private string loginToken;
        /// <summary>
        /// 登录标识
        /// </summary>
        protected Guid? LoginToken
        {
            get 
            {
                Guid token = new Guid();
                if (Session[LoginTokenKey] != null && Guid.TryParse(Session[LoginTokenKey].ToString(),out token))
                {
                    return token;
                }
                return null;
            }
            set 
            {
                Session[LoginTokenKey] = value;
            }
        }

     


        /// <summary>
        /// 当前导航类别
        /// </summary>
        //public EnumHelp.NavType CurrNavType
        //{
        //    get
        //    {
        //        if (ViewBag.Nav != null)
        //        {
        //            return EnumHelp.ConvertToEnum<EnumHelp.NavType>(ViewBag.Nav);
        //        }
        //        return EnumHelp.NavType.Home;
        //    }
        //    set
        //    {
        //        ViewBag.Nav = value;
        //    }
        //}

        /// <summary>
        /// 低于ie8的浏览器，跳转到特殊页面
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.Browser.IsMobileDevice
                && !filterContext.HttpContext.Request.UserAgent.ToLower().Contains("micromessenger")
                && filterContext.HttpContext.Request.UserAgent.ToLower().Contains("msie")
                && filterContext.HttpContext.Request.Browser.MajorVersion < 8)
            {
                base.OnActionExecuting(filterContext);

                filterContext.HttpContext.Response.Write("为了更好地浏览本网站的内容，请您升级浏览器！");
                filterContext.HttpContext.Response.End();

                //var url = "~/Home/Tip";
                //filterContext.Result = Redirect(url);
                return;

            }


            //用于后台目录树定位
            //var areaName = filterContext.RouteData.DataTokens["Area"];
            //if (areaName != null && areaName.ToString() == "Adm")
            //{
            //    string folder = filterContext.HttpContext.Request.QueryString["folder"];
            //    if (!string.IsNullOrWhiteSpace(folder))
            //    {
            //        Session["admfolder"] = folder;
            //    }
            //}

        }


        /// <summary>
        /// 使用当前控制器，执行一个视图页，并返回生成的html
        /// </summary>
        /// <param name="partialView"></param>
        /// <returns></returns>
        public string RenderPartial(string partialView)
        {
            using (System.IO.StringWriter s = new System.IO.StringWriter())
            {
                var view = ViewEngines.Engines.FindPartialView(ControllerContext, partialView).View;
                if (view == null)
                    throw new ArgumentException("无法找到匹配的视图页面：" + partialView);
                var con = new ViewContext(ControllerContext, view, ViewData, TempData, s);
                view.Render(con, s);
                return s.ToString();
            }
        }
        public void RenderPartial(string partialView,TextWriter tw)
        {
                var view = ViewEngines.Engines.FindPartialView(ControllerContext, partialView).View;
                if (view == null)
                    throw new ArgumentException("无法找到匹配的视图页面：" + partialView);
                var con = new ViewContext(ControllerContext, view, ViewData, TempData, tw);
                view.Render(con, tw);
        }

        public ISimplePagingInfo GetPagingInfo(string defSort = null)
        {
            var query=ControllerEx.GetQueryInfo(Request.Params);
            if (query.OrderFirst==null)
            {
            query.OrderFirst=defSort;
            }
            return query;
        }

        public ViewDto<T> GetDto<T>(T data,int total)
        {
           var dto= ViewDto.Create(data);
            var pageInfo = GetPagingInfo();
            dto.Page = pageInfo.PageNum;
            dto.Rows = pageInfo.PageSize;
            dto.OrderFirst = pageInfo.OrderName;
            dto.IsDescFirst = pageInfo.IsDesc;
            dto.Total =total;
            return dto;
        }

        readonly string ReturnUrlParamName = "ReturnUrl";

        /// <summary>
        /// 跳转到url中的返回地址，如果没有则跳转到指定地址
        /// </summary>
        /// <param name="defUrl"></param>
        /// <returns></returns>
      public   ActionResult RedirectToReturnUrl(string defUrl)
        {
            if (Request.AsAjaxRequest())
            {
                return Json(ReState.Success.Create());
            }
            var reUrl = Request.QueryString[ReturnUrlParamName];
            if (string.IsNullOrWhiteSpace(reUrl))
            {
                return Redirect(defUrl);
            }
            return Redirect(reUrl);
        }
        /// <summary>
        /// 返回执行状态，如果为ajax返回状态json字符
        /// </summary>
        /// <param name="rs">状态</param>
        /// <param name="url">成功跳转的页面</param>
        /// <param name="errorView">错误视图</param>
        /// <returns></returns>
        public ActionResult ReturnByState(ResultState rs, string url, string errorView = null)
        {
            if (Request.AsAjaxRequest())
            {
                return Json(rs);
            }
            if (rs.State < 0)
            {
                ViewData.ReHandleState(rs);
                return errorView == null ? View() : View(errorView);
            }
            return Redirect(url);
        }


        /// <summary>
        /// 如果成功，弹出提示，并跳转到指定地址，失败则回到本页
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult ReturnPromptByState(ResultState rs, string url, string errorView = null)
        {
            if (Request.AsAjaxRequest())
            {
                return Json(rs);
            }
            if (rs.State < 0)
            {
                ViewData.ReHandleState(rs);
                return errorView == null ? View() : View(errorView);
            }
            var content = string.Format("<script>alert('{0}'); window.location.href = '{1}';</script>", rs.Msg, url);
            return Content(content);
        }
        public ActionResult ReturnErrorPrompt(string msg, string errorView = null)
        {
            var state = ReState.Error.Create(msg);
            return ReturnPromptByState(state, "", errorView);
        }
        public ActionResult PromptToUrl(string msg, string url, string view = null)
        {
            var content = string.Format("<script>alert('{0}'); window.location.href = '{1}';</script>", msg, url);
            if (view == null)
            {
                return Content(content);
            }
            else
            {
                Response.Write(content);
                return View(view);
            }
        }

        /// <summary>
        /// 提示错误信息，并保留在原页面
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult FailAndAlert(string msg)
        {
            var content = string.Format("<script>alert('{0}'); window.history.go(-1);</script>", msg);
            return Content(content);
        }

        /// <summary>
        /// 给出一个成功提示信息，然后跳转到指定页
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult ReturnPrompt(string msg, string url)
        {
            var state = ReState.Success.Create(msg);
            return ReturnPromptByState(state, url);
        }

        /// <summary>
        /// 设置一个页面返回状态，用于页面显示控制器执行状况
        /// </summary>
        /// <param name="rs"></param>
        public void ReHandleState(ResultState rs)
        {
            ViewData.ReHandleState(rs);
        }
        /// <summary>
        /// 设置一个页面返回状态，用于页面显示控制器执行状况
        /// </summary>
        /// <param name="rs">状态</param>
        /// <param name="msg"></param>
        public void ReHandleState(ReState rs, string msg)
        {
            ViewData.ReHandleState(rs.Create(msg));
        }

        /// <summary>
        /// 获取控制器执行状态
        /// </summary>
        /// <returns></returns>
        public ResultState ReHandleState()
        {
            return ViewData.ReHandleState();
        }

    


        /// <summary>
        /// 检查文件扩展名并保存，如果名称为null则生成随机名称
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <param name="allowExt">使用|分割的扩展名列表,要包含.</param>
        /// <param name="name">不包含扩展名的文件新名称</param>
        /// <returns>新文件名称，包含扩展名</returns>
        internal protected string CheckSaveAs(HttpPostedFileBase file, string path, string allowExt, string name = null)
        {
            if (file == null || allowExt == null)
            {
                return null;
            }
            var extName = Path.GetExtension(file.FileName);
            if(string.IsNullOrEmpty(extName))
            {
                return null;
            }
            var index = allowExt.IndexOf(extName);
            if (index < 0)
            {
                return null;
            }
            // 创建文件存放的文件路径，如果没有，创建该路径
            string folder = HttpContext.Server.MapPath(path);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            name = name ?? DateTime.Now.Ticks.ToString();
            var newName = name + extName;
            string uploadPath = Path.Combine(folder, newName);
            while (System.IO.File.Exists(uploadPath))
            {
                name += "A";
                newName = name + extName;
                uploadPath = Path.Combine(folder, newName);  
            }
            
            file.SaveAs(uploadPath);
            return newName;
        }

        public string ModelStateErrors()
        {
            System.Text.StringBuilder sbErrors = new System.Text.StringBuilder();
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    for (int i = item.Errors.Count - 1; i >= 0; i--)
                    {
                        sbErrors.Append(item.Errors[i].ErrorMessage);
                        sbErrors.Append("<br/>");
                    }
                }
            }
            return sbErrors.ToString();
        }

        ///// <summary>
        ///// 通过总记录数得出总分页数
        ///// </summary>
        ///// <param name="total">记录总数</param>
        ///// <returns></returns>
        //public int GetPageCount(int total)
        //{
        //    int pageSize = SiteConfig.ConfigInfo.PageSize;
        //    int result = total % pageSize > 0 ? total / pageSize + 1 : total / pageSize;
        //    if (result <= 0)
        //    {
        //        result = 1;
        //    }
        //    return result;
        //}

        //public int GetPageCount(int total,int pageSize)
        //{
        //    int result = total % pageSize > 0 ? total / pageSize + 1 : total / pageSize;
        //    if (result <= 0)
        //    {
        //        result = 1;
        //    }
        //    return result;
        //}

        public JsonResult JsonEx(object data) {
            return new JsonExResult() { Data = data };
        }


        #region 通用cookie操作

        /// <summary>
        /// 推荐人id,保存时的key
        /// </summary>
        protected readonly string UShareId = "UShareId";

        string tmpCookieKey = "tmpVal";
        /// <summary>
        /// 获取用于保存临时数据的cookie
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetTmpValByCookie(string name)
        {
            var val = Request.Cookies[tmpCookieKey];
            if (val == null)
            {
                return null;
            }

            return val.Values[name];
        }
        protected HttpCookie SetTmpValByCookie(string name, string val)
        {
            var cookie = Response.Cookies[tmpCookieKey];
            if (cookie == null)
            {
                cookie = new HttpCookie(tmpCookieKey); 
                Response.AppendCookie(cookie);
            }
            cookie.Values[name] = val; 
            cookie.Expires = DateTime.Now.AddYears(1);  //分享人id保存一年
            return cookie;
        } 
        #endregion

       
    }
    public class JsonExResult : JsonResult
    {
      
      public override void ExecuteResult(ControllerContext context)
      {
         //确认是否用于响应HTTP-GET请求
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Compare(context.HttpContext.Request.HttpMethod, "GET", true)  == 0)
           {
               throw new InvalidOperationException();
           }

            HttpResponseBase response = context.HttpContext.Response;
          //设置媒体类型和编码方式
         response.ContentType = string.IsNullOrEmpty(this.ContentType) ?"application/json" : this.ContentType;
         if (this.ContentEncoding != null)
           {
             response.ContentEncoding = this.ContentEncoding;
           }
    
           //创建JavaScriptSerializer将数据对象序列化成JSON字符串并写入当前HttpResponse
           if (null == this.Data)return;
           response.Write(SimpleJson.Serializer(this.Data));        
      }
    }

    public class BaseController<TEntity> : BaseController where TEntity : IDbEntity
    {

    }
}
